package org.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by tedzy on 2015/5/12.
 * Sha1计算
 */
public class Sha1 {
    public static String getSha1(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(data.getBytes());
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return byte2hex(bytes);
    }

    public static byte[] hmacSha1(String text, String key){
        try {
            SecretKey sk = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(sk);

            byte[] signedText = text.getBytes("UTF-8");
            return mac.doFinal(signedText);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ignored) {

        }
        return null;
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
